import java.util.*;

public class Main {
    public static void main(String[] args) {

    }
}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) return ret;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        //判断当前层是否是偶数层,是偶数层将当前层的所有节点进行逆序
        int level = 1;
        while(!queue.isEmpty()){
            int size = queue.size();//记录当前的层节点个数
            List<Integer> layer = new ArrayList<>();
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                layer.add(node.val);
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
            }
            if(level % 2 == 0) Collections.reverse(layer);
            ret.add(layer);
            level++;
        }
        return ret;
    }
}